package com.yh.tea.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yh.tea.entity.RoleResource;
import com.yh.tea.mapper.RoleResourceMapper;
import com.yh.tea.model.AssignResource;
import com.yh.tea.service.RoleResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yh.tea.utiity.ResponseResult;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yh
 * @since 2024-03-04
 */
@Service
public class RoleResourceServiceImpl extends ServiceImpl<RoleResourceMapper, RoleResource> implements RoleResourceService {

    @Override
    public ResponseResult getResourceList(Long roleId) {
        List<RoleResource> roleResources =list(new QueryWrapper<RoleResource>().eq("role_id",roleId));
        List<Long> resources=new ArrayList<>();
        for (RoleResource roleResource : roleResources) {
            resources.add(roleResource.getResourceId());
        }
        return ResponseResult.success("查询成功",resources);
    }

    @Override
    public ResponseResult assignResources(AssignResource assignResource) {
        //第一步遍历查询====》得到 两个数组===》该删除的===》该增加的
        Long roleId=assignResource.getRoleId();
        //接收来的resourceIds
        List<Long> resourceIds=assignResource.getResourceIds();
        //原来有的resourceIds
        List<RoleResource> roleResourceList=  list(new QueryWrapper<RoleResource>().eq("role_id",roleId));
        List<Long> originalResourceIds=new ArrayList();
        for (RoleResource roleResource : roleResourceList) {
           originalResourceIds.add(roleResource.getResourceId());
        }

        List buDong=new ArrayList();
        buDong.addAll(resourceIds);
        buDong.retainAll(originalResourceIds);

        List<Long> delList=new ArrayList<>();
        delList.addAll(originalResourceIds);
        delList.removeAll(buDong);

        List<Long> addList=new ArrayList<>();
        addList.addAll(resourceIds);
        addList.removeAll(buDong);

        //添加，
        for (Long aLong : addList) {
           save(new RoleResource(roleId,aLong,1));
        }
        //删除
        for (Long aLong : delList) {
            remove(new QueryWrapper<RoleResource>().eq("resource_id",aLong).eq("role_id",roleId));
        }

        return ResponseResult.success("修改成功");
    }


}
